package RecursiveSearcher;

import java.util.List;
import java.util.ArrayList;
/**
 * @ClassName LC17
 * @Description TODO
 * @Author ZJX
 * @Date 2024/9/17 18:18
 * @Version 1.0
 */
public class LC17 {
    private static final String[] MAPPING = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();

        if (digits == null || digits.length() == 0){
            return null;
        }

        backtrack(result,digits,0,new StringBuilder());

        return result;
    }

    private void backtrack(List<String> result, String digits, int index, StringBuilder cur) {
        if (index == digits.length()){
            result.add(cur.toString());
            return;
        }

        // 获取当前数字
        char digit = digits.charAt(index);
        String letters = MAPPING[digit - '0'];  // 获取数字对应的字母

        // 遍历当前数字对应的所有字母
        for (char letter : letters.toCharArray()) {
            cur.append(letter); // 选择一个字母
            backtrack(result, digits, index + 1, cur); // 递归处理下一个数字
            cur.deleteCharAt(cur.length() - 1); // 撤销选择
        }
    }
}

